<template>
	<view @touchstart="handleTouchStart">
		<cu-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">采购单查询</block>
		</cu-custom>
		<view class="container">
			<!-- 条件查询输入框 -->
			<view class="search-bar">
				<!-- 输入框 -->
				<view class="input-wrapper">
					<input v-model="searchVal" placeholder="请输入查询数据" @input="handleInput" :focus="focusStateProduct"
						style="background-color: white;" autofocus />
					<!-- 清除按钮 -->
					<!-- 				<button 
				  v-if="searchVal" 
				  class="clear-button" 
				  @click="clearSearchKeyword"
				>
				  X
				</button> -->
				</view>
				<button @click="search">查询</button>
			</view>
			<!-- 条件查询输入框 -->
			<view class="search-bar">
				<!-- 输入框 -->
				<view class="title">供应商:</view>
				<view class="action some-class" style="width: 60%;margin-right: 40px;margin-left: 10px;">
					<!-- 					<uni-data-select v-model="myFormData.supplierId" style="font-size: 12px;height: 30px;"
								:localdata="sortSupps" @change="changeSupp"></uni-data-select> -->
					<!-- style="flex: 1; height: 20rpx; border: 1rpx solid #ccc; font-size: 30rpx;" -->
					<custom-down-search ref="selSupp" 
					:options="custListText" 
					:localdata="custList" 						
					:value="searchCustId" 
					@changeInput="changeSupp"
					v-model="searchCustId"></custom-down-search>
					<!-- <MySelect v-model="myFormData.supplierId" dictCode='yn'></MySelect> -->
				</view>
			</view>

			<!-- 表格展示查询结果 -->
			<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
				@selection-change="selectionChange">
				<uni-tr>
					<uni-th width="20" align="center">序号</uni-th>
					<uni-th width="150" align="center">采购单号</uni-th>
					<uni-th align="center">厂商名称</uni-th>
					<uni-th width="150" align="center">下单日期 </uni-th>
					<uni-th width="150" align="center">需求日期</uni-th>
					<uni-th width="150" align="center">金额</uni-th>
					<uni-th width="150" align="center">税额</uni-th>
					<uni-th width="150" align="center">状态</uni-th>
					<!-- <uni-th width="204" align="center">设置</uni-th> -->
				</uni-tr>
				<uni-tr v-for="(item, index) in tableData" :key="index">
					<uni-td>{{ index + 1 }}</uni-td>
					<uni-td>{{ item.poNo }}</uni-td>
					<uni-td align="center">{{ item.supplierId_dictText }}</uni-td>
					<uni-td>{{ item.poDate }}</uni-td>
					<uni-td>{{ item.deliveryDate }}</uni-td>
					<uni-td>{{ item.amount }}</uni-td>
					<uni-td>{{ item.taxAmount }}</uni-td>
					<uni-td>{{ item.status_dictText }}</uni-td>
					<!-- 					<uni-td>
						<view class="uni-group">
							<button class="uni-button" size="mini" type="primary">修改</button>
							<button class="uni-button" size="mini" type="warn">删除</button>
						</view>
					</uni-td> -->
				</uni-tr>
			</uni-table>
			<view class="uni-pagination-box">
				<uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total"
					@change="change" />
			</view>
		</view>
		<view class="example-body">
			<drawer :show="subOrderDrawerShow" @cancel="subOrderCancel" @ensure="subOrderEnsure">
				<view style="margin-top: 140rpx;">
					<uni-table ref="itemTable" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
						@selection-change="selectionDrawChange">
						<uni-tr>
							<uni-th width="50" align="center">序号</uni-th>
							<!-- 						<uni-th width="150" align="center">工单号</uni-th>
						<uni-th width="150" align="center">客户</uni-th> -->
							<uni-th width="120" align="center">物料编码</uni-th>
							<uni-th width="150" align="center">规格</uni-th>
							<uni-th width="120" align="center">物料描述</uni-th>
							<uni-th width="120" align="center">物料名称</uni-th>
							<uni-th width="120" align="center">自定义名称</uni-th>
							<uni-th width="150" align="center">版本</uni-th>
							<uni-th width="120" align="center">数量</uni-th>
							<uni-th width="120" align="center">下单日期</uni-th>
							<uni-th width="120" align="center">需求日期</uni-th>
						</uni-tr>
						<uni-tr v-for="(item1, index) in itemChilds" :key="index">
							<uni-td>{{ (index + 1) }}</uni-td>
							<!-- 						<uni-td>{{ item1.workOrderNumber }}</uni-td>
						<uni-td>{{ item1.customerShortName }}</uni-td> -->
							<uni-td>{{ item1.code }} </uni-td>
							<uni-td> {{item1.materialModel}} </uni-td>
							<uni-td> {{item1.description}} </uni-td>
							<uni-td> {{item1.name}} </uni-td>
							<uni-td> {{item1.realName}} </uni-td>
							<uni-td> {{item1.materialVer}} </uni-td>
							<uni-td> {{item1.qty}} </uni-td>
							<uni-td> {{item1.poDate ? item1.poDate : '' }} </uni-td>
							<uni-td> {{item1.deliveryDate ? item1.deliveryDate : '' }} </uni-td>
						</uni-tr>
					</uni-table>
				</view>
			</drawer>
		</view>
	</view>
</template>

<script>
	import api from '@/api/api.js'
	import {
		USER_INFO,
		SASS_DOMAIN_ID,
		SASS_TENANT_ID,
		SASS_DOMAIN_NAME
	} from "@/common/util/constants"
	import CustomDownSearch from '@/components/my-componets/custom-down-search.vue'
	import tableData from '../workorder/table/tableData.js'

	export default {
		name : "queryPurchaseOrder",
		components: {
			CustomDownSearch,
		},
		data() {
			return {
				subOrderDrawerShow: false,
				searchKeyword: '',
				searchVal: '',
				searchCustId: null,
				tableData: [],
				itemChilds: [],
				custList: [],
				custListText: [],
				// 每页数据量
				pageSize: 10,
				// 当前页
				pageCurrent: 1,
				// 数据总量
				total: 0,
				loading: false,
				url: {
					custList: '/bas/basSupplier/list',
					list: '/pom/pomPurchaseOrder/list',
					queryById: '/pom/pomPurchaseOrder/queryPomPurchaseOrderItemByMainId',
					saveShareLink : '/opm/opmOutsourceProcess/saveShareLink'
				}
			};
		},
		onLoad() {
			this.selectedIndexs = []
			this.getData(1)
		},
		created() {
			this.getCusts()
		},
		methods: {
			changeSupp(val) {
				this.searchCustId = val
			},
			handleTouchStart(event) {
				// 获取触摸点的信息
				const touch = event.touches[0];
		 	const x = touch.clientX;
				const y = touch.clientY;
				console.log(`触摸开始，坐标为：(${x}, ${y})`);
				this.$refs.selSupp.handelDropDown(x, y)
			},
			getCusts() {
				console.log("beging find cust.")
				this.$http.get(
					this.url.custList, {
						params: {
							pageSize: 1000,
							status: 1
						}
					}).then(res => {
					console.log("res::cust>", res)
					if (res.data.result.records) {
						let data = res.data.result.records
						this.custList = []
						data.forEach((item) => {
							let obj = {
								value: item.id,
								text: item.shortName
							}
							this.custList.push(obj)
							this.custListText.push(obj.text)
						})
					}
				})
			},
			handleDetail(id) {
				let that = this
				let params = {
					'id': id,
				}
				this.loading = true
				this.$http.get(this.url.queryById, {
					params: params
				}).then(res => {

					this.loading = false
					that.itemChilds = res.data.result.records || res.data.result;
					console.log(that.itemChilds)
					console.log(res.data.result)
					that.$nextTick(() => {
						this.subOrderDrawerShow = true
					})

				})
			},
			subOrderCancel() {
				console.log('您点击了取消按钮')
				this.subOrderDrawerShow = false;
			},
			//确定
			subOrderEnsure() {
				console.log('您点击了确定按钮')
				this.subOrderDrawerShow = false;
			},
			setFocusProduct() {
				let that = this
				this.$nextTick(() => {
					setTimeout(() => {
						that.focusStateProduct = true
					}, 1000)
				})

			},
			handleInput() {

			},
			selectedItems() {
				return this.selectedIndexs.map(i => this.tableData[i])
			},
			// 多选
			selectionDrawChange(e) {

			},
			selectionChange(e) {
				console.log(e.detail.index)
				this.selectedIndexs = e.detail.index
				if (this.selectedIndexs.length == 1) {
					let rows = this.selectedItems()
					this.handleDetail(rows[0].id)
				}
			},
			//批量删除
			delTable() {
				console.log(this.selectedItems())
			},
			// 分页触发
			change(e) {
				this.$refs.table.clearSelection()
				this.selectedIndexs.length = 0
				this.getData(e.current)
			},
			clearSearchKeyword() {
				debugger
				this.searchVal = ''
			},
			// 搜索
			search() {
				this.getData(1, this.searchVal)
			},
			getData(pageCurrent, value = '') {
				debugger
				this.pageCurrent = pageCurrent
				let that = this
				let params = {
					'queryName': value,
					'pageNo': this.pageCurrent,
					'pageSize': this.pageSize,
					'column': 'createTime,updateTime',
					'order': 'desc',
				}
				let superArr = []
				superArr.push({"rule":"eq","type":"string","val":'3',"field":"status"})
				// superArr.push({"rule":"eq","type":"string","val":this.supplierId,"field":"po.supplierId"})
				params.superQueryMatchType = 'and'
				params.superQueryParams = encodeURIComponent(JSON.stringify(superArr))
				
				this.loading = true
				this.$http.get(this.url.list, {
					params: params
				}).then(res => {
					this.loading = false
					this.tableData = res.data.result.records || res.data.result;
					console.log(this.tableData)
					this.setFocusProduct()
					if (res.data.result.total) {
						this.total = res.data.result.total
					} else {
						this.total = 0
					}
				})
			},
			// 获取数据
			getData1(pageCurrent, value = '') {
				this.loading = true
				this.pageCurrent = pageCurrent
				this.request({
					pageSize: this.pageSize,
					pageCurrent: pageCurrent,
					value: value,
					success: res => {
						// console.log('data', res);
						this.tableData = res.data
						this.total = res.total
						this.loading = false
					}
				})
			},
			// 伪request请求
			request(options) {
				const {
					pageSize,
					pageCurrent,
					success,
					value
				} = options
				let total = tableData.length
				let data = tableData.filter((item, index) => {
					const idx = index - (pageCurrent - 1) * pageSize
					return idx < pageSize && idx >= 0
				})
				if (value) {
					data = []
					tableData.forEach(item => {
						if (item.name.indexOf(value) !== -1) {
							data.push(item)
						}
					})
					total = data.length
				}

				setTimeout(() => {
					typeof success === 'function' &&
						success({
							data: data,
							total: total
						})
				}, 500)
			},
			onShareAppMessage: async function() {
				debugger
				if (!this.searchCustId) {
					this.$tip.toast("没选择供应商，不可以分享链接！");
					return {
						title: "没有分享成功，供应商数据没填！",
						path: '/pages/report/suppQueryPurchaseOrder',
						success: (res) => {
							console.log('分享成功', res);
						},
						fail: (res) => {
							console.log('分享失败', res);
						}
					};
				} else {
					let uuid = this.generateUUID();
					let companyName = uni.getStorageSync(SASS_DOMAIN_NAME);
					let tenantId = uni.getStorageSync(SASS_TENANT_ID);
					let domainId = uni.getStorageSync(SASS_DOMAIN_ID);
					// let supplierId = this.selectedSupp[0].value;
					let param = {
						'uuid': uuid.toString(),
						'tenantId': tenantId,
						'supplierId': this.searchCustId
					};
					debugger
					console.log(param)
					param = JSON.stringify(param);
					this.$tip.loading();
					try {
						let custObj = this.custList.filter((p,k)=>{return p.value == this.searchCustId})
						debugger
						const res = await this.$http.post(this.url.saveShareLink, param);
						this.$tip.loaded();
						console.log(res)
						if (res.data.success) {
							companyName = res.data.result.companyName || companyName
							this.$tip.toast('提交成功');
							return {
								title: (companyName ? companyName : tenantId) + ',发送给:' + custObj[0].text +
									'采购单信息查询。',
								path: '/pages/report/suppQueryPurchaseOrder?uuid=' + uuid + '&tenantId=' + tenantId +
									'&supplierId=' + this.searchCustId,
								success: (res) => {
									console.log('分享成功', res);
								},
								fail: (res) => {
									console.log('分享失败', res);
								}
							};
						} else {
							this.$tip.error('提交失败');
							return {
								title: "没有分享成功，数据提交失败！",
								path: '/pages/report/suppQueryPurchaseOrder',
								success: (res) => {
									console.log('分享成功', res);
								},
								fail: (res) => {
									console.log('分享失败', res);
								}
							};
						}
					} catch (error) {
						this.$tip.loaded();
						this.$tip.error('提交失败');
						return {
							title: "没有分享成功，数据提交失败！",
							path: '/pages/report/suppQueryPurchaseOrder',
							success: (res) => {
								console.log('分享成功', res);
							},
							fail: (res) => {
								console.log('分享失败', res);
							}
						};
					}
				}
			},
			// 假设使用简易方式生成 uuid
			generateUUID() {
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					var r = Math.random() * 16 | 0,
						v = c == 'x' ? r : (r & 0x3 | 0x8);
					return v.toString(16);
				});
			},

		}
	};
</script>

<style scoped>
	.input-wrapper {
		position: relative;
		flex: 1;
	}

	.input-wrapper input {
		width: 100%;
		height: 40px;
		padding: 0 10px;
		border: 1px solid #ccc;
		border-radius: 5px;
		margin-right: 10px;
		box-sizing: border-box;
		/* 确保内边距和边框不会增加元素的宽度 */
	}

	.clear-button {
		position: absolute;
		top: 50%;
		right: 20px;
		/* 调整按钮的位置，避免被输入框的边框遮挡 */
		transform: translateY(-50%);
		background: none;
		border: none;
		color: #999;
		font-size: 16px;
		cursor: pointer;
		z-index: 1;
		/* 确保按钮在最上层，不会被其他元素遮挡 */
	}

	.container {
		padding: 6px;
	}

	.search-bar {
		display: flex;
		align-items: center;
		margin-bottom: 20px;
	}

	.search-bar input {
		flex: 1;
		height: 40px;
		padding: 0 10px;
		border: 1px solid #ccc;
		border-radius: 5px;
		margin-right: 10px;
	}

	.search-bar button {
		height: 40px;
		padding: 0 20px;
		background-color: #007aff;
		color: #fff;
		border: none;
		border-radius: 5px;
		align-items: center;
		line-height: 40px;
	}

	uni-table {
		margin-bottom: 20px;
	}

	uni-pagination {
		display: flex;
		justify-content: center;
	}
</style>
